#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
from random import random
import random

import requests
import csv
import shutil
from Config.config import getConfig

class api_answer():

    def __init__(self):
        self.headers = eval(getConfig("admin", "cookie"))
        self.base_url = getConfig("base_url", "training_url")

    # headers = {
    #     "Cookie": "TrainingPlatform-sid=s%3AktzuUWAR8wHuF0ip0BQM4oQGRFcYw7Xk.BH27g4hdsHBpFX%2FYMYZLOuuTLTO0nZGCepTHUuWzXJs; local-state={%22_id%22:%225f02f2349fd8b6fa72e727cf%22%2C%22username%22:%22admin%22%2C%22email%22:%22admin@forensix.cn%22%2C%22roles%22:[%22admin%22]%2C%22avatar%22:null%2C%22isReset%22:false%2C%22isModifyPersonal%22:true}; XSRF-TOKEN=AqjlsHWE-jNzPnqI44GvNrtSjsNFcPD2myqk",
    #     "X-XSRF-TOKEN": "AqjlsHWE-jNzPnqI44GvNrtSjsNFcPD2myqk",
    # }


    def api_answer(self, com_id):

        # 根据竞赛名称查询
        # find_id_url = self.base_url +'/competitions?skip=0&limit=10&text={}'.format(com_name)
        # response_json = requests.get(find_id_url, headers=self.headers).json()
        # com_id = response_json['competitions'][0]['_id']


        url = self.base_url +'/competition/info?_id={}'.format(com_id)

        response_json = requests.get(url, headers=self.headers).json()
        paper_id = response_json['testPaper'][0]['_id']

        paper_url = self.base_url +"/testPaper/detail?_id={}".format(paper_id)
        paper_response = requests.get(paper_url, headers=self.headers).json()
        paper_response = paper_response['sections']

        answer_dir = r'D:/pythoncode/trainning/common/anser_csv/{}'.format(com_id)

        if os.path.exists(answer_dir) == False:
            os.mkdir(answer_dir)

        with open(answer_dir+'/answer.csv', 'w+', newline='') as w:
            csv_writer = csv.writer(w)
            # 分组的数量
            lens = len(paper_response)
            for i in range(lens):
                # 分组中的题目数量
                flens = len(paper_response[i]['questions'])
                for j in range(flens):
                    csv_writer.writerow([paper_response[i]['questions'][j]['no'], paper_response[i]['questions'][j]['answer'], paper_response[i]['questions'][j]['score'], paper_response[i]['questions'][j]['type']])

        # 获取套题总分
        # url = self.base_url + '/competition/info?_id={}'.format(com_id)
        # response_json = requests.get(url, headers=self.headers).json()
        # socre = response_json['testPaper']['score']
        return answer_dir# , socre
        # shutil.copy("anser_csv/answer.csv", "anser_csv/part_answer.csv")
        # shutil.copy("anser_csv/answer.csv", "anser_csv/wrong_answer.csv")
        # shutil.copy("anser_csv/answer.csv", "anser_csv/blanck_part_answer.csv")
        # shutil.copy("anser_csv/answer.csv", "anser_csv/only_option_part_answer.csv")

    def set_answer(self, dir, num, name):
        with open(dir+'/answer.csv', 'r+', newline='') as r:
            # 获取需要重置题目的题号
            randnum = random.randint(1, num)
            a = list(range(1, num+1))
            random.shuffle(a)
            num_list = a[:randnum]
            # print(num_list)
            csv_reader = csv.reader(r)
            x = 1


            with open(dir+'/{}.csv'.format(name), 'w+', newline='') as w:
                csv_writer = csv.writer(w)
                score = 0
                total_score = int(0)

                for i in csv_reader:
                    if x in num_list:
                        option = random.choice(["A", "B", "None"])
                        if option != "None" and i[3] == 'subjective':
                            tmp = int(random.choice([i[2], 0, int(i[2])-1]))
                        elif option != "None" and i[1] == option and i[3] != 'subjective':
                            tmp = i[2]
                        else:
                            tmp = '0'
                        csv_writer.writerow([i[0], repr(option), tmp])
                        score += int(tmp)
                        if option != "None":
                            total_score += int(i[2])
                    else:
                        tmp = i[2] if i[3] != 'subjective' else random.choice([i[2], 0, int(i[2])-1])
                        csv_writer.writerow([i[0], repr(i[1]), tmp])
                        score += int(tmp)
                        total_score += int(i[2])

                    x+=1
        return score,total_score


        
# if __name__ == '__main__':
#     tmp = api_answer().api_answer('测试不同种类状态显示')
#     # TODO 需要算出来每种答案对应的分数
#     api_answer().set_answer(tmp, 20, '20')